package at.fhj.mobsecdev.cookit.webrequests;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import at.fhj.mobsecdev.cookit.R;
import at.fhj.mobsecdev.cookit.util.Constants;
import at.fhj.mobsecdev.cookit.util.LoadingIndicator;

/**
 * Web service call to login a user
 */
public class LoginWebCall extends AsyncTask<String, Void, Object> {

	private SharedPreferences credentialsSharedPreferences;
	private Login caller;
	private ProgressDialog dialog;
	private Context context;
	
	public LoginWebCall(SharedPreferences credentialsSharedPreferences, Login caller, Activity activity)
	{
		this.credentialsSharedPreferences = credentialsSharedPreferences;
		this.caller = caller;
		this.context = activity;
	}
	
	protected void onPreExecute() {
	    dialog = new LoadingIndicator(context).createIndicator();
	    dialog.show();
	}
	
	@Override
	protected Object doInBackground(String... params) {
		String webServiceUrl = WebServiceUrls.REST_URL + WebServiceUrls.VALIDATE_LOGIN;
		
		try {			
			String timestamp = GetTimestampWebCall.getTimestamp();

			String username = credentialsSharedPreferences.getString(Constants.PREFERENCE_USERNAME, "");
			String passwordHash = credentialsSharedPreferences.getString(Constants.PREFERENCE_PASSWORDHASH, "");
			
			List<NameValuePair> parameter = new LinkedList<NameValuePair>();
			parameter.add(new BasicNameValuePair("username", username));
			parameter.add(new BasicNameValuePair("hash", HashUtils.hashCredentials(username, passwordHash, timestamp)));
			
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(webServiceUrl);
			
			request.setEntity(new UrlEncodedFormEntity(parameter));
			
			HttpResponse response = client.execute(request);

			int httpStatusCode = response.getStatusLine().getStatusCode();
			if(httpStatusCode == HttpStatus.SC_OK) //credentials are correct
			{
				return Boolean.TRUE;
			}
			else if(httpStatusCode == HttpStatus.SC_BAD_REQUEST) //credentials are incorrect
			{
				return Boolean.FALSE;
			}
			else
			{
				return new IllegalStateException(context.getResources().getString(R.string.web_service_communication_problem));
			}
		}
		catch(IllegalStateException e)
		{
			return new IllegalStateException(context.getResources().getString(R.string.web_service_could_not_connect));
		}
		catch(ClientProtocolException e) {
			return new IllegalStateException(context.getResources().getString(R.string.web_service_could_not_connect));
		}
		catch(IOException e) {
			return new IllegalStateException(context.getResources().getString(R.string.web_service_could_not_connect));
		}
	}
	
	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		if(result instanceof Boolean)
		{
			Boolean resultValue = (Boolean) result;
			
			if(resultValue == true)
			{
				caller.credentialsCorrect();
			}
			else
			{
				caller.credentialsIncorrect();
			}
		}
		else if(result instanceof IllegalStateException)
		{
			RuntimeException e = (RuntimeException)result;
			caller.webServiceCallFailed(e);
		}
	}
	
	/**
	 * Interface, which specifies the methods that are called after the webservice call. The calls forward either the list of
	 * parsed recipes or error information.
	 */
	public interface Login
	{
		void credentialsCorrect();
		
		void credentialsIncorrect();
		
		void webServiceCallFailed(Exception e);
	}
}
